<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>用户管理</title>
		<!-- jQuery -->
		<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
		<!-- Element-UI CSS -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
		<script src="../js/authChecker.js"></script>
		<style>
			/* 粉色主题 */
			.el-button--primary,
			.el-button--primary:hover,
			.el-button--primary:focus {
				background-color: #FF1493;
				border-color: #FF1493;
			}

			body {
				margin: 0;
				padding: 20px;
				background: #f2f2f2;
				font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Arial, sans-serif;
			}

			.search-box {
				background: #fff;
				padding: 15px;
				border-radius: 4px;
				margin-bottom: 15px;
			}

			.user-avatar {
				width: 40px;
				height: 40px;
				border-radius: 50%;
				object-fit: cover;
			}

			/* 批量切换状态按钮透明 */
			.el-button--warning {
				background-color: transparent !important;
				border-color: #E6A23C !important;
				color: #E6A23C !important;
			}

			/* 添加商品按钮透明 */
			.el-button--primary {
				background-color: transparent !important;
				border-color: #FF1493 !important;
				color: #FF1493 !important;
			}

			.el-button--warning:hover,
			.el-button--warning:focus {
				background-color: #FF1493;
				/* 悬停时背景颜色 */
				color: #fff;
				/* 悬停时文字颜色 */
			}

			.page-title {
				font-size: 22px;
				color: #333;
				margin-bottom: 20px;
				font-weight: 600;
			}

			/* 加载动画 */
			.loading-overlay {
				position: fixed;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.5);
				display: flex;
				justify-content: center;
				align-items: center;
				z-index: 9999;
				display: none;
			}

			.loading-spinner {
				border: 4px solid #f3f3f3;
				border-top: 4px solid #FF1493;
				border-radius: 50%;
				width: 40px;
				height: 40px;
				animation: spin 1s linear infinite;
			}

			@keyframes spin {
				0% {
					transform: rotate(0deg);
				}

				100% {
					transform: rotate(360deg);
				}
			}

			/* 消息提示 - 仿示例样式 */
						.message {
						    position: fixed;
						    top: 20px;
						    left: 50%;
						    transform: translateX(-50%);
						    padding: 10px 20px;
						    border-radius: 4px;
						    /* 关键修改：背景、文字、边框色 */
						    background-color: #f0f9eb; 
						    border: 1px solid #c2e7b0; 
						    color: #67c23a;             
						    z-index: 9999;
						    display: none;
						    align-items: center;
						    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
						    transition: all 0.3s ease;
						    opacity: 0;
						}
						
						/* 对勾图标样式 */
						.message i {
						    font-family: "element-icons" !important;
						    content: "\E652"; /* Element UI 成功图标 Unicode */
						    margin-right: 8px;
						    font-size: 16px;
						    color: #67c23a;
						}
						
						/* 显示动画 */
						.message.show {
						    opacity: 1;
						    transform: translateX(-50%) translateY(0);
						}
						
						/* 隐藏动画 */
						.message.hide {
						    opacity: 0;
						    transform: translateX(-50%) translateY(-20px);
						}
			/* 表格样式 */
			.el-table {
				width: 100%;
				border-collapse: collapse;
				margin-bottom: 15px;
			}

			.el-table th,
			.el-table td {
				padding: 12px 0;
				border: 1px solid #ebeef5;
				text-align: center;
			}

			.el-table th {
				background-color: #f5f7fa;
				color: #909399;
				font-weight: bold;
			}

			.el-table tr:hover {
				background-color: #f5f7fa;
			}

			/* 分页样式 */
			.el-pagination {
				margin-top: 15px;
				text-align: right;
			}

			.el-pagination button {
				padding: 0 6px;
				margin: 0 5px;
				border: 1px solid #dcdfe6;
				background: #fff;
				border-radius: 4px;
				cursor: pointer;
			}

			.el-pagination button:disabled {
				cursor: not-allowed;
				opacity: 0.5;
			}

			.el-tag {
				padding: 0 10px;
				border-radius: 4px;
				font-size: 12px;
				line-height: 24px;
			}

			.el-tag-success {
				background-color: #f0f9eb !important;
				border-color: #e1f3d8 !important;
				color: #00aa00 !important;
			}

			.user-status-deleted {
				background-color: #f0f9eb !important;
				border-color: #e1f3d8 !important;
				color: #2d2d2d !important;
			}

			/* 专门针对用户状态的样式 */
			.user-status-deleted {
				background-color: #f0f0f0 !important;
				border-color: #d9d9d9 !important;
				color: #999 !important;
				cursor: pointer;
			}

			.el-tag--danger {
				background-color: #fef0f0;
				border-color: #fde2e2;
				color: #f56c6c;
			}

			/* 表单样式 */
			.el-form--inline .el-form-item {
				margin-right: 10px;
				margin-bottom: 0;
				vertical-align: top;
			}

			.el-form-item__label {
				padding: 0 12px 0 0;
				color: #606266;
				line-height: 40px;
			}

			.el-input__inner {
				width: 100%;
				padding: 8px 15px;
				border: 1px solid #dcdfe6;
				border-radius: 4px;
				font-size: 14px;
				color: #606266;
				outline: none;
				height: 40px;
				line-height: 40px;
			}

			.el-select {
				display: inline-block;
				position: relative;
			}

			.el-pagination button {
				padding: 0 6px;
				margin: 0 5px;
				border: 1px solid #dcdfe6;
				background: #fff;
				border-radius: 4px;
				cursor: pointer;
			}

			.el-pagination button:disabled {
				cursor: not-allowed;
				opacity: 0.5;
			}
		</style>
	</head>
	<body>
		<div class="page-title">用户管理</div>
		<div id="app">
			<!-- 搜索区 -->
			<div class="search-box">
				<form class="el-form el-form--inline" id="searchForm" onsubmit="return false;">
					<div class="el-form-item">
						<label class="el-form-item__label">用户名</label>
						<div class="el-form-item__content">
							<input type="text" class="el-input__inner" id="username" placeholder="请输入用户名">
						</div>
					</div>

					<div class="el-form-item">
						<label class="el-form-item__label">手机号</label>
						<div class="el-form-item__content">
							<input type="text" class="el-input__inner" id="userphone" placeholder="请输入手机号">
						</div>
					</div>

					<div class="el-form-item">
						<label class="el-form-item__label">状态</label>
						<div class="el-form-item__content">
							<select class="el-select__inner" id="status" style="width:110px;height:40px;">
								<option value="">全部状态</option>
								<option value="1">正常</option>
								<option value="0">已删除</option>
							</select>
						</div>
					</div>

					<div class="el-form-item">
						<div class="el-form-item__content">
							<button type="button" class="el-button el-button--primary"
								onclick="handleSearch()">搜索</button>
							<button type="button" class="el-button" onclick="resetSearch()"
								style="color:#ff85a2;border-color:#ff85a2;">重置</button>
						</div>
					</div>
				</form>

				<div style="margin-top:10px;">
					<button type="button" class="el-button el-button--warning" id="batchToggleBtn" disabled
						onclick="handleBatchToggle()">批量切换状态</button>
				</div>
			</div>

			<!-- 表格 -->
			<table class="el-table" id="userTable">
				<thead>
					<tr>
						<th style="width:50px;"><input type="checkbox" id="selectAll" onclick="toggleSelectAll()"></th>
						<th style="width:80px;">用户ID</th>
						<th style="width:80px;">用户头像</th>
						<th style="width:120px;">用户名</th>
						<th style="width:150px;">手机号</th>
						<th>OpenID</th>
						<th style="width:90px;">状态</th>
						<th style="width:150px;">注册时间</th>
					</tr>
				</thead>
				<tbody>
					<!-- 动态内容将通过JS填充 -->
				</tbody>
			</table>
			<div class="el-pagination">
				<button class="el-pagination__first" onclick="firstPage()" id="firstBtn">首页</button>
				<button class="el-pagination__prev" onclick="prevPage()" id="prevBtn">上一页</button>第
				<span class="el-pagination__current" id="currentPage"
					style="width: 10px; text-align: center; font-size: 20px; margin: -2px -4px -20px -10px;">1</span>页
				<button class="el-pagination__next" onclick="nextPage()" id="nextBtn">下一页</button>
				<button class="el-pagination__last" onclick="lastPage()" id="lastBtn">尾页</button>
				<span class="el-pagination__total">共 <span id="totalItems">0</span> 条</span>
			</div>
		</div>

		<!-- 加载动画 -->
		<div class="loading-overlay" id="loadingOverlay">
			<div class="loading-spinner"></div>
		</div>

		<!-- 消息提示 -->
		<div class="message" id="message"></div>

		<script>
			// 在页面加载时立即检查登录状态
			if (!checkAdminLogin()) {
				// 登录检查失败，阻止页面继续加载
				console.log('登录验证失败，已跳转至登录页');
			} else {
				// 全局变量
				let tableData = [];
				let selectedRows = [];
				let currentPage = 1;
				let limit = 10;
				let total = 0;

				// 页面加载完成后初始化
				$(document).ready(function() {
					fetchData();
				});

				// 显示加载中
				function showLoading() {
					$('#loadingOverlay').css('display', 'flex');
				}

				// 隐藏加载中
				function hideLoading() {
					$('#loadingOverlay').hide();
				}

			

				// 获取用户数据
				function fetchData() {
					showLoading();

					const params = {
						page: currentPage,
						limit: limit
					};

					if ($('#username').val()) {
						params.username = $('#username').val();
					}

					if ($('#userphone').val()) {
						params.userphone = $('#userphone').val();
					}

					if ($('#status').val()) {
						params.status = $('#status').val();
					}

					$.ajax({
						url: 'http://localhost:8887/user/SelectUserHou',
						type: 'GET',
						data: params,
						success: function(response) {
							hideLoading();
							if (response.code === 200) {
								tableData = response.data.user.list || [];
								total = response.data.user.total || 0;
								console.log(tableData);
								renderTable();
								updatePagination();
							} else {
								showMessage('error', response.msgerr || '获取数据失败');
							}
						},
						error: function(xhr, status, error) {
							hideLoading();
							showMessage('error', '请求失败: ' + error);
						}
					});
				}
// 显示消息（带动画）
				function showMessage(type, message) {
				    const msgElement = $('#message');
				    msgElement.removeClass().addClass(`message message-${type}`);
				    msgElement.text(message);
				    
				    // 先应用离开动画重置位置
				    msgElement.removeClass('show').addClass('hide');
				    setTimeout(() => {
				        // 再切换进入动画
				        msgElement.removeClass('hide').addClass('show');
				        msgElement.show();
				        
				        // 3秒后自动隐藏
				        setTimeout(() => {
				            msgElement.removeClass('show').addClass('hide');
				            setTimeout(() => {
				                msgElement.hide();
				            }, 300);
				        }, 3000);
				    }, 300);
				}
				// 渲染表格
				function renderTable() {
					const tbody = $('#userTable tbody');
					tbody.empty();

					tableData.forEach(function(row) {
						const registydate = formatDate(row.registydate);
						console.log(registydate);
						const tr = $(`
                    <tr>
                        <td><input type="checkbox" data-id="${row.userid}" onchange="handleRowSelection(this, ${row.userid})"></td>
                        <td>${row.userid}</td>
                        <td><img src="${row.userurl || '../img/userimg3.png'}" class="user-avatar"></td>
                        <td>${row.username}</td>
                        <td>${row.userphone}</td>
                        <td>${row.openid}</td>
                        <td>
                           <span class="el-tag ${row.status == '0' ? 'user-status-deleted' : 'el-tag-success'}"
                                 onclick="toggleStatus(${row.userid}, '${row.status}')"
                                 style="cursor: pointer;">
                               ${row.status == '0' ? '已删除' : '正常'}
                           </span>
                        </td>
                        <td>${registydate}</td>
                    </tr>
                `);

						tbody.append(tr);
					});

					// 更新批量操作按钮状态
					$('#batchToggleBtn').prop('disabled', selectedRows.length === 0);
				}
				// 格式化日期函数
				function formatDate(dateString) {
					if (!dateString) return '';

					// 假设后端返回的日期是 ISO 格式（如 2025-08-06T12:34:56）
					const date = new Date(dateString);

					// 如果日期无效，返回空字符串
					if (isNaN(date.getTime())) return '';

					// 格式化为 YYYY-MM-DD
					const year = date.getFullYear();
					const month = String(date.getMonth() + 1).padStart(2, '0');
					const day = String(date.getDate()).padStart(2, '0');

					return `${year}-${month}-${day}`;
				}

				// 上一页
				function prevPage() {
					if (currentPage > 1) {
						currentPage--;
						fetchData();
					}
				}

				// 下一页
				function nextPage() {
					if (currentPage * limit < total) {
						currentPage++;
						fetchData();
					}
				}

				// 首页
				function firstPage() {
					if (currentPage > 1) {
						currentPage = 1;
						fetchData();
					}
				}

				// 尾页
				function lastPage() {
					if (currentPage * limit < total) {
						currentPage = Math.ceil(total / limit);
						fetchData();
					}
				}

				// 更新分页状态
				function updatePagination() {
					$('#currentPage').text(currentPage);
					$('#totalItems').text(total);

					const prevBtn = $('#prevBtn');
					const nextBtn = $('#nextBtn');
					const firstBtn = $('#firstBtn');
					const lastBtn = $('#lastBtn');

					prevBtn.prop('disabled', currentPage <= 1);
					nextBtn.prop('disabled', currentPage * limit >= total);
					firstBtn.prop('disabled', currentPage <= 1);
					lastBtn.prop('disabled', currentPage * limit >= total);
				}

				// 搜索
				function handleSearch() {
					currentPage = 1;
					fetchData();
				}

				// 重置搜索
				function resetSearch() {
					$('#username').val('');
					$('#userphone').val('');
					$('#status').val('');
					handleSearch();
				}

				// 处理行选择
				function handleRowSelection(checkbox, userid) {
					if (checkbox.checked) {
						selectedRows.push(userid);
					} else {
						selectedRows = selectedRows.filter(id => id !== userid);
					}

					// 更新全选状态
					updateSelectAllStatus();

					// 更新批量操作按钮状态
					$('#batchToggleBtn').prop('disabled', selectedRows.length === 0);
				}

				// 全选/取消全选
				function toggleSelectAll() {
					const selectAll = $('#selectAll').prop('checked');
					const checkboxes = $('#userTable tbody input[type="checkbox"]');

					checkboxes.each(function() {
						$(this).prop('checked', selectAll);
						const userid = parseInt($(this).data('id'));

						if (selectAll) {
							if (!selectedRows.some(id => id === userid)) {
								selectedRows.push(userid);
							}
						} else {
							selectedRows = selectedRows.filter(id => id !== userid);
						}
					});

					$('#batchToggleBtn').prop('disabled', selectedRows.length === 0);
				}

				// 更新全选状态
				function updateSelectAllStatus() {
					const checkboxes = $('#userTable tbody input[type="checkbox"]');
					const selectAll = $('#selectAll');

					if (checkboxes.length === 0) {
						selectAll.prop('checked', false);
						return;
					}

					const allChecked = checkboxes.toArray().every(checkbox => checkbox.checked);
					selectAll.prop('checked', allChecked);
				}

				// 批量切换状态
				function handleBatchToggle() {
					const ids = selectedRows;

					if (ids.length === 0) return;

					if (confirm(`确定切换 ${ids.length} 位用户的状态吗？`)) {
						showLoading();

						$.ajax({
							url: 'http://localhost:8887/user/updateUserHou',
							type: 'POST',
							contentType: 'application/json',
							data: JSON.stringify({
								ids: ids
							}),
							success: function(response) {
								hideLoading();
								if (response.code === 200) {
									showMessage('success', '状态切换成功');
									fetchData();
									selectedRows = [];
									$('#selectAll').prop('checked', false);
								} else {
									showMessage('error', response.msgerr || '批量切换失败');
								}
							},
							error: function(xhr, status, error) {
								hideLoading();
								showMessage('error', '请求失败: ' + error);
							}
						});
					}
				}

				// 切换单个用户状态
				function toggleStatus(userid, currentStatus) {
					const newStatus = currentStatus === '0' ? '1' : '0';
					const tip = newStatus === '0' ? '设为异常' : '设为正常';
					console.log(userid + "" + currentStatus);
					if (confirm(`确定将用户 ${tip}？`)) {
						showLoading();

						$.ajax({
							url: 'http://localhost:8887/user/updateUserHou',
							type: 'POST',
							contentType: 'application/json',
							data: JSON.stringify({
								ids: [userid],
								status: newStatus
							}),
							success: function(response) {
								hideLoading();
								if (response.code === 200) {
									showMessage('success', '状态切换成功');
									fetchData();
								} else {
									showMessage('error', response.msgerr || '切换失败');
								}
							},
							error: function(xhr, status, error) {
								hideLoading();
								showMessage('error', '请求失败: ' + error);
							}
						});
					}
				}
			}
		</script>
	</body>
</html>